﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Church.Common;
using Church.Models.Shared;
using Church.Resources;
using DataBaseLayer.Dto;
using MvcContrib;

namespace Church.Controllers
{
	public class FotoClubController : Controller
	{
		#region Actions

		public ActionResult Index(int? model)
		{
			return View(model);
		}

		public ActionResult Puzzles(int? pageNumber)
		{
			var model = new PuzzlesModel();
			FillPuzzlesModel(model, pageNumber ?? 1);
			return View(model);
		}

		public ActionResult Pager(int? pageNumber)
		{
			var model = new PagerModel
			{
				CurrentPage = pageNumber.HasValue ? pageNumber.GetValueOrDefault() : 1,
				TotalCountItems = AppContext.ServiceFactory.GalleriesService.GetCountFotoClubGalleries()
			};
			return View(model);
		}

		public ActionResult Slider(int? id)
		{
			var model = AppContext.ServiceFactory.GalleriesService.GetFotoClubGalleryById(id.GetValueOrDefault(), Constants.DEFAULT_COUNT_PUZZLES);
			if (model != null && model.IsFotoclub)
				return View(model);
			return this.RedirectToAction(a => a.Index(null));
		}

		#endregion

		#region Internal Implementation

		private void FillPuzzlesModel(PuzzlesModel model, int pageNumber)
		{
			if (model != null)
			{
				var data = AppContext.ServiceFactory.GalleriesService.GetFotoClubGalleriesByPageNumber(pageNumber - 1, Constants.DEFAULT_COUNT_PUZZLES) ?? new List<GalleryData>();
				for (var item = 0; item < data.Count() && item < Constants.DEFAULT_COUNT_PUZZLES; item++)
				{
					model.Puzzles[item].Header = data.ElementAt(item).Name;
					if (data.ElementAt(item).Images != null && data.ElementAt(item).Images.Any())
						model.Puzzles[item].ImageUrl = (data.ElementAt(item).Images.FirstOrDefault(i => i.IsDefault)
							?? data.ElementAt(item).Images.FirstOrDefault()).Url;
					model.Puzzles[item].Url = new UrlHelper(Request.RequestContext).Action(
						"Slider",
						"FotoClub",
						new RouteValueDictionary { { "id", data.ElementAt(item).GalleryId } });
				}
				model.FooterHelp = "Фотоклуб прихожан";
			}
		}

		#endregion
	}
}
